from rest_framework import serializers

from app.models import City, MachineRoom, Host


class CityModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = City
        fields = '__all__'
        read_only_fields = ['created_at', 'updated_at']


class MachineRoomModelSerializer(serializers.ModelSerializer):
    city_name = serializers.CharField(source='city.name', read_only=True)

    class Meta:
        model = MachineRoom
        fields = '__all__'
        read_only_fields = ['created_at', 'updated_at']


class HosModelSerializer(serializers.ModelSerializer):
    city_name = serializers.CharField(source='city.name', read_only=True)
    machine_room_name = serializers.CharField(source='machine.name', read_only=True)

    class Meta:
        model = Host
        fields = '__all__'
        read_only_fields = ['created_at', 'updated_at', 'host_password', 'is_ping', 'last_ping_time']

    def validate_ip_address(self, value):
        instance = self.instance
        if Host.objects.filter(ip_address=value).exclude(pk=instance.pk if instance else None).exists():
            raise serializers.ValidationError(f"IP 地址 {value} 已经存在")
        return value
